<template>
  <el-button size="mini" type="primary" :disabled="isDisabled" :loading="loading" @click="getPhoneCode">{{ btnText }}</el-button>
</template>

<script>
import { sendValidCode } from '@/api/admin/captcha';

export default {
  props: {
    phone: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isDisabled: false,
      countDownTime: 60,
      loading: false
    };
  },
  computed: {
    btnText() {
      let text = '获取验证码';
      if (this.loading) {
        text = '发送短信中';
      } else if (this.isDisabled) {
        text = `${this.countDownTime}s重新获取`;
      }
      return text;
    }
  },
  methods: {
    getPhoneCode() {
      if (!this.phone) {
        this.$notify({
          title: '警告',
          message: '请输入手机号码',
          type: 'warning'
        });
        return;
      }
      this.loading = true;
      sendValidCode({ agentId: this.phone }).then(res => {
        this.loading = false;
        const result = res.data;
        if (result.code === 0) {
          this.sendCode();
          this.$notify({
            title: '成功',
            message: '发送成功',
            type: 'success'
          });
        }
      });
    },
    sendCode() {
      if (this.countDownTime === 0) {
        this.isDisabled = false;
        this.countDownTime = 60;
      } else {
        this.isDisabled = true;
        this.countDownTime--;
        setTimeout(() => {
          this.sendCode();
        }, 1000);
      }
    }
  }

};
</script>

<style lang="scss" scoped>

</style>
